
package com.xiaobo.bodada.job.cycle;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.benmanes.caffeine.cache.Cache;
import com.xiaobo.bodada.mapper.WebsiteAnalysisMapper;
import com.xiaobo.bodada.model.entity.WebsiteAnalysis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.xiaobo.bodada.constant.CommonConstant.WEBSITE_ANALYSIS_KEY;

/**
 * 增量同步网站统计到 数据库
 * @author xiaobo
 * 
 */

@Component
@Slf4j
public class IncSyncWebsiteAnalysisToDB {
    @Resource
    private Cache<String, String> caffeine;
    @Resource
    private WebsiteAnalysisMapper websiteAnalysisMapper;
    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void run() {
        log.info("开始同步网站分析数据");
        caffeine.asMap().forEach((key,value)->{
            if(key.contains(WEBSITE_ANALYSIS_KEY)){
                WebsiteAnalysis websiteAnalysis = JSONUtil.toBean(value, WebsiteAnalysis.class);
                String[] split = key.split(":");
                String ip = split[1];
                WebsiteAnalysis selected = websiteAnalysisMapper.selectOne(Wrappers.lambdaQuery(WebsiteAnalysis.class)
                        .eq(WebsiteAnalysis::getVisitIp, ip)
                        .eq(WebsiteAnalysis::getVisitDate, websiteAnalysis.getVisitDate()));
                if(selected==null){
                    websiteAnalysisMapper.insert(websiteAnalysis);
                }else{
                    log.error("已存在ip记录{}",key);
                }
            }
        });
    }
}

